<template>
	<view v-if="canIUse">
		<view v-if="!showPop" class="head-view">
			<image class='head-image' src="../../static/logo.png" mode='scaleToFill'></image>
			<text  class='title-text'>拾亲</text>
		    <text class='app-apply-text'>申请获取以下权限</text>
		    <text v-if="!hasAuthorization" class='content-userinfo-text'>获得您的公开信息(昵称，头像、地区等)</text>
			<text v-if="hasAuthorization" class='content-userphone-text'>获得您微信绑定的手机号</text>
			<button v-if="!hasAuthorization&&!canIUseGetUserProfile" class='auth-userinfo-btn' type="primary" 
			open-type='getUserInfo' lang="zh_CN" @getuserinfo="wxGetUserInfo">获取授权</button>
			
			<button v-if="!hasAuthorization&&canIUseGetUserProfile" class='auth-userinfo-btn' type="primary"
			lang="zh_CN" @click="wxGetUserProfile">获取授权</button>
			
			<button v-if="hasAuthorization" class='auth-userphone-btn' type="primary" style="background-color: #FF5E06;"
			lang="zh_CN" open-type="getPhoneNumber" @getphonenumber="getPhoneNumber">手机号授权</button>
		</view>
		<InputXingMingPop v-if="showPop" @returnInputXingMingPop="returnInputXingMingPop"></InputXingMingPop>
	</view>
	<view v-else>请升级微信版本</view>
</template>

<script>
	import {wxlogin,wxUserInfo,wxSessionKey} from "./wxlogin.js"
	import request from './request.js';
	import InputXingMingPop from '../../components/input-xing-ming-pop/input-xing-ming-pop.vue'
	export default {
		components: {
			InputXingMingPop
		},
		data() {
			return {
				canIUse: true,
				hasAuthorization:false,
				// 可以使用新版本获取用户资料方法
				canIUseGetUserProfile: false,
				unionid:"",
				openId:"",
				sessionKey:"",
				phone:"",
				avatarUrl:"",
				nickName:"",
				gender:1,
				userInfo:{},
				loginInfo:{},
				phoneParams:{ 
					cloudID:"",
					ivdata:"",
					encrypdata:""
				},
				loginStatus:false,
				phoneStatus:false,
				treeId:"",
				appInviteId:"",
				showPop:false,
				userPQD:"",
				userToken:"",
				Signature:"",
			}
		},
		onLoad: function (options) {
			try{
				this.share.shareType=1
				this.treeId=options.treeId
				this.appInviteId=uni.getStorageSync("shiqin-user-appInviteId")
				this.init()
			}catch(e){
				console.log("init错误信息：",e)
			}
		},
		methods: {
			init(){
				var that=this;
				var version = uni.getSystemInfoSync().SDKVersion
				if (uni.getUserProfile() && this.compareVersion(version, '2.16.0') >= 0) {
					this.canIUseGetUserProfile = true;
				} else {
					this.canIUseGetUserProfile = false;
				}
				wxlogin().then(res=>{
					that.loginInfo=res
					var userinfo=uni.getStorageSync("shiqin-user")
					if(userinfo.nickname){
						//获取app用户信息
						that.getAppUserInfo()
					}else{
						try{
							//获取登陆授权和手机号授权
							if(that.canIUseGetUserProfile){
								that.wxGetUserProfile()
							}else{
								that.wxGetUserInfo()
							}
						}catch(e){
							//适配电脑端登陆
							that.wxGetUserInfo()
						}
						that.getSessionKey(res.code)
					}
				})
			},
			modifyName(){
				var xing=uni.getStorageSync("shiqin-user-xing")
				var ming=uni.getStorageSync("shiqin-user-ming")
				var that=this;
				request.post('api/user/profile_user',{
					PQD_B:that.userPQD,
					token:that.userToken,
					set_key:"name",
					set_val:xing+"-"+ming,
					is_lunar:"",
					PQD:that.userPQD,
				}).then(data=>{
					that.modifyUserInfo()
				})
			},
			modifyUserInfo(){
				var sex=uni.getStorageSync("shiqin-user-sex")
				var that=this;
				request.post('api/user/profile_user',{
					PQD_B:that.userPQD,
					token:that.userToken,
					set_key:"gender",
					set_val:sex,
					is_lunar:"",
					PQD:that.userPQD,
				}).then(data=>{
					this.getAppUserInfo()
				})
			},
			getAppUserInfo(){
				var that=this;
				request.post('api/user/index',{
					PQD:that.userPQD,
					token:that.userToken,
				}).then(data=>{
					//获取用户信息，pqd存在则进入首页
					if(data.PQD&&data.nickname){
						if(data.nickname){
							uni.setStorageSync("shiqin-user",data)
							uni.setStorageSync("shiqin-user-xing",data.nickname)
							uni.setStorageSync("shiqin-user-ming",data.nickcname)
							uni.setStorageSync("shiqin-user-sex",data.gender)
							uni.$emit('refrashHomeData')
							uni.$emit('refrashMineData')
							uni.navigateBack({
								delta:1
							})
						}else{
							that.showPop=true
							uni.setNavigationBarTitle({
								title:"完善个人信息"
							})
						}
					}
				})
			},
			wxGetUserInfo:function(){
				var that=this
				wxUserInfo().then(res=>{
					that.userInfo=res
					if(res&&res.userInfo){
						//不需要授权，已经获取用户信息
						that.hasAuthorization=true
						that.avatarUrl=this.userInfo.userInfo.avatarUrl
						that.nickName=this.userInfo.userInfo.nickName
					}else{
						//需要授权，未获得用户信息
						that.isAuthorization=false
					}
				})
				
				this.loginStatus = true
			},
			wxGetUserProfile:function(){
				var that=this
				uni.getUserProfile({
					desc:'登录',
					success:(res)=>{
						console.log("canIUseGetUserProfile：",JSON.stringify(res))
						that.userInfo=res
						if(res&&res.userInfo){
							//不需要授权，已经获取用户信息
							that.hasAuthorization=true
							that.avatarUrl=this.userInfo.userInfo.avatarUrl
							that.nickName=this.userInfo.userInfo.nickName
						}else{
							//需要授权，未获得用户信息
							that.isAuthorization=false
						}
					}
				})
				this.loginStatus = true
			},
			getPhoneNumber (e) {
				if(!e.detail.encryptedData){
					return
				}
				if(!e.detail.iv){
					return
				}
				if(!e.detail.cloudID){
					return
				}
				var that=this
				this.appUtil.load("登录中...")
				this.phoneParams.encrypdata = e.detail.encryptedData
				this.phoneParams.ivdata = e.detail.iv
				this.phoneParams.cloudID = e.detail.cloudID
				var user_wx={
					openid:this.openId,
					unionid:this.unionid,
					photo:this.avatarUrl,
					uname:this.nickName
				}
				var info_wx={
					encryptedData:this.phoneParams.encrypdata,
					iv:this.phoneParams.ivdata,
					sessionKey:this.sessionKey
				}
				request.post('api/user/mobilelogin',{
					platform:"wxapp",
					mobile:JSON.stringify(info_wx),
					extions:JSON.stringify(user_wx),
					yaoqingid:this.appInviteId,
					treeid:this.treeId
				}).then(data=>{
					if(data.PQD){
						that.userPQD=data.PQD
						that.userToken=data.token
						if(data.nickname){
							uni.setStorageSync("shiqin-user",data)
							uni.setStorageSync("shiqin-user-xing",data.nickname)
							uni.setStorageSync("shiqin-user-ming",data.nickcname)
							uni.setStorageSync("shiqin-user-sex",data.gender)
							uni.$emit('refrashHomeData')
							uni.$emit('refrashMineData')
							uni.navigateBack({
								delta:1
							})
						}else{
							that.showPop=true
							uni.setNavigationBarTitle({
								title:"完善个人信息"
							})
						}
					}
				})
			},
			getSessionKey(code){
				var that=this
				this.appUtil.load("登录中...")
				wxSessionKey(code).then(data=>{
					uni.setStorageSync("shiqin-user-openId",data.openid)
					that.openId=data.openid
					that.sessionKey=data.session_key
					that.unionid=data.unionid
					that.getThridLogin()
				})
			},
			getThridLogin(){
				var that=this
				var user_wx={
					openid:this.openId,
					unionid:this.unionid,
					photo:this.avatarUrl,
					uname:this.nickName
				}
				request.post("api/user/third_v2",{
					platform:"wxapp",
					code:this.openId,
					extions:JSON.stringify(user_wx),
				}).then(data=>{
					//获取用户信息
					if(data.PQD){
						that.userPQD=data.PQD
						that.userToken=data.token
						if(data.nickname){
							uni.setStorageSync("shiqin-user",data)
							uni.setStorageSync("shiqin-user-xing",data.nickname)
							uni.setStorageSync("shiqin-user-ming",data.nickcname)
							uni.setStorageSync("shiqin-user-sex",data.gender)
							uni.$emit('refrashHomeData')
							uni.$emit('refrashMineData')
							uni.navigateBack({
								delta:1
							})
						}else{
							that.showPop=true
							uni.setNavigationBarTitle({
								title:"完善个人信息"
							})
						}
					}
				})
			},
			returnInputXingMingPop() {
				this.appUtil.load("加载中...")
				this.modifyName()
			},
			// 查看微信版本号--版本比较 
			compareVersion(v1, v2) {
				v1 = v1.split('.')
				v2 = v2.split('.')
				const len = Math.max(v1.length, v2.length)
				while (v1.length < len) {
				  v1.push('0')
				}
				while (v2.length < len) {
				  v2.push('0')
				}
				for (let i = 0; i < len; i++) {
				  const num1 = parseInt(v1[i])
				  const num2 = parseInt(v2[i])
				  if (num1 > num2) {
					return 1
				  } else if (num1 < num2) {
					return -1
				  }
				}
				return 0
			},
		}
	}
</script>

<style>
	@import "index.css";
</style>
